<?php
/*
* This module is based on Login & Register Panel (Ajax based) by Marghoob Suleman.
* Original module topic on Prestashop forum: http://www.prestashop.com/forums/topic/57675-module-login-register-panel-ajax-based/.
*/

/* SSL Management */
$useSSL = true;

include(dirname(__FILE__).'../../../config/config.inc.php');
include(dirname(__FILE__).'../../../init.php');

    if (version_compare(_PS_VERSION_,'1.5','<'))
    {
        if ($cookie->isLogged())
	        Tools::redirect('my-account.php');
	}
	else
	{
	    if ($customer->isLogged())
	        Tools::redirect('index.php?controller=my-account');
	}

$errors = array();
$actionLogin = trim(Tools::getValue('actionlogin'));
if ($actionLogin=='login')
{
	$passwd = trim(Tools::getValue('passwd_ajax'));
	$email = trim(Tools::getValue('email_ajax'));

	if (empty($email)) {
		$msg = Tools::displayError('E-mail address is required');
	}
	elseif (!Validate::isEmail($email))
		$msg = Tools::displayError('Invalid e-mail address');
	elseif (empty($passwd))
		$msg = Tools::displayError('Password is required');
	elseif (Tools::strlen($passwd) > 32)
		$msg = Tools::displayError('Password is too long');
	elseif (!Validate::isPasswd($passwd))
		$msg = Tools::displayError('Invalid password');
	else
	{
		$customer = new Customer();
		$authentication = $customer->getByemail(trim($email), trim($passwd));
		/* Handle brute force attacks */
		//sleep(1);
		if (!$authentication OR !$customer->id)
			$msg = Tools::displayError('Authentication failed');
		else
		{
			$cookie->id_customer = (int)($customer->id);
			$cookie->customer_lastname = $customer->lastname;
			$cookie->customer_firstname = $customer->firstname;
			$cookie->logged = 1;
			$cookie->passwd = $customer->passwd;
			$cookie->email = $customer->email;
			if (Configuration::get('PS_CART_FOLLOWING') AND (empty($cookie->id_cart) OR Cart::getNbProducts($cookie->id_cart) == 0))
				$cookie->id_cart = (int)(Cart::lastNoneOrderedCart((int)($customer->id)));
			$id_address = (int)(Address::getFirstCustomerAddressId((int)($customer->id)));
			$cookie->id_address_delivery = $id_address;
			$cookie->id_address_invoice = $id_address;
			$msg = "success";
		}
	}
	if($msg=='success') {
		//$msg = Module::hookExec('blockmyaccount');
	}
        echo $msg;
    exit;
}
if (Tools::getValue('email_create'))
{
	$email = Tools::getValue('email_create');
	if (!Validate::isEmail($email))
		$msg = Tools::displayError('Invalid e-mail address');
	elseif (Customer::customerExists($email))
		$msg = Tools::displayError('An account is already registered with this e-mail, please fill with another one.');
	else
	{
		$msg = "success";
	}
        echo $msg;
    exit;
}
?>